package com.activities;


import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.Animations.AnimUtil;
import com.Data.Notifications;
import com.Data.Notifications.onGetNotificationsCountCompleted;
import com.Data.Tag;
import com.Data.Tag.onSearchTagCompleted;
import com.Data.User;
import com.Data.User.onGetUserInfoCompleted;
import com.Downloaders.ProfilePictureDownloader;
import com.Downloaders.ProfilePictureDownloader.onProfilePictureDownloaded;
import com.Listeners.MenuClickListener;
import com.Managers.FragmentManagerClass;
import com.Managers.UserManagerClass;
import com.SoapClasses.SoapUtil;
import com.TextFormat.UtilFonts;
import com.activities.ActivityMenu.iconTextArrayAdapter.RowType; // $codepro.audit.disable unnecessaryImport
import com.shareup.R;


public class ActivityMenu extends ListFragment {

    public static int SELECTED_MENU_START = SoapUtil.MODE_NEWS;

    public boolean popularPending = false;

    private iconTextArrayAdapter adapter;

    private ImageView edit;

    private List<Item> items;

    private ListView list;

    private TextView name;

    private RelativeLayout notificationContainer;

    private TextView notificationText;

    private ProgressBar pload;

    private ImageView profile;

    private View v;

    //
    public static class Header implements Item {

        private final String name;

        public Header(String name) {

            this.name = name;
        }

        @Override
        public View getView(LayoutInflater inflater, View convertView) {

            View view;
            TextView text = null;
            if (convertView == null) {
                view = inflater.inflate(R.layout.item_menu_header, null);

            }
            else {
                view = convertView;
            }
            text = (TextView) view.findViewById(R.id.item_menu_header_text);
            UtilFonts.setTextBoldFont(text);
            text.setText(name);
            view.setTag(MenuClickListener.ITEM_TYPE_HEADER);

            return view;
        }

        @Override
        public int getViewType() {

            return RowType.HEADER_ITEM.ordinal();
        }
    }

    public static class iconTextArrayAdapter extends ArrayAdapter<Item> {

        private final LayoutInflater mInflater;

        public enum RowType {
            HEADER_ITEM, LIST_ITEM
        }

        public iconTextArrayAdapter(Context context, List<Item> items) {

            super(context, 0, items);
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getItemViewType(int position) {

            return getItem(position).getViewType();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            return getItem(position).getView(mInflater, convertView);
        }

        @Override
        public int getViewTypeCount() {

            return RowType.values().length;
        }
    }

    // //////////////////////////////////////////////////////////////////
    public static interface Item {

        public View getView(LayoutInflater inflater, View convertView);

        public int getViewType();
    }

    public static class ListItem implements Item {

        private final int iconRes;

        private final String text;

        private final int type;

        // private boolean wasHigh = false;

        public ListItem(String text1, int iconRes, int type) {

            this.text = text1;
            this.iconRes = iconRes;
            this.type = type;
        }

        @Override
        public View getView(LayoutInflater inflater, View convertView) {

            View view;
            if (convertView == null) {
                int resource = R.layout.item_menu;

                view = inflater.inflate(resource, null);
                // Do some initialization
            }
            else {
                view = convertView;
            }
            //
            TextView text1 = (TextView) view.findViewById(R.id.row_m_title);
            UtilFonts.setTextRegularFont(text1);
            ImageView icon = (ImageView) view.findViewById(R.id.row_icon);
            ImageView refresh = (ImageView) view.findViewById(R.id.row_refresh);
            refresh.setOnClickListener(new RefreshIconClick(type));
            text1.setText(text);
            icon.setImageResource(iconRes);
            view.setTag(type);

            if (type == SoapUtil.MODE_NEWS) {
                MenuClickListener.currentSelectedView = view;
                MenuClickListener.highlightCurrentRow(view);
            }
            return view;
        }

        @Override
        public int getViewType() {

            return RowType.LIST_ITEM.ordinal();
        }
    }

    public static class ListItemPopular implements Item {

        private final String counter;

        private final String tag;

        public ListItemPopular(String text, String count) {

            this.tag = text;
            this.counter = count;
        }

        @Override
        public View getView(LayoutInflater inflater, View convertView) {

            View view;
            if (convertView == null) {
                view = inflater.inflate(R.layout.item_menu_popular, null);
                // Do some initialization
            }
            else {
                view = convertView;
            }

            TextView text1 = (TextView) view.findViewById(R.id.item_menu_popular_text);
            TextView count = (TextView) view.findViewById(R.id.item_menu_popular_counter);
            UtilFonts.setTextRegularFont(count, text1);
            text1.setText(tag);
            count.setText(counter);

            view.setTag(tag);
            return view;
        }

        @Override
        public int getViewType() {

            return RowType.LIST_ITEM.ordinal();
        }
    }

    static class RefreshIconClick implements OnClickListener {

        private final int MODE;

        public RefreshIconClick(int mODE) {

            MODE = mODE;

        }

        @Override
        public void onClick(View v) {

            Log.e("MODE", MODE + "");
            switch (MODE) {
                case SoapUtil.MODE_FOLLOWERS:
                    FragmentManagerClass.aFollow.loadFollows();
                    break;
                case SoapUtil.MODE_NEWS:
                    if (SoapUtil.MENU_VIEW == SoapUtil.MODE_MINE) {
                        FragmentManagerClass.aMine.refresh();
                    }
                    else {
                        FragmentManagerClass.aExplore.refresh();
                    }
                    break;
                default:
                    FragmentManagerClass.aExplore.refresh();
                    break;
            }
            FragmentManagerClass.sMenu.toggle();
        }
    }

    public ImageView getProfile() {

        return profile;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        inicializar();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        v = inflater.inflate(R.layout.activity_menu, null);
        return v;
    }

    public void setProfile(Bitmap profile) {

        this.profile.setImageBitmap(profile);
    }

    public void setUserInfo(User result) {

        UserManagerClass uClass = new UserManagerClass(getActivity());
        uClass.saveInfo(result);
        name.setText(result.getRealName());
    }

    public void updateNotifications() {

        Notifications nt = new Notifications(0);
        nt.setCallbackGetCount(new onGetNotificationsCountCompleted() {

            @Override
            public void Completed(String result) {

                result = result.replace("\"", "");
                AnimUtil.animateFadeIn(notificationContainer);
                notificationText.setText(result);
                if (!result.equals("0")) {
                    if (FragmentManagerClass.aMain != null) {
                        FragmentManagerClass.aMain.getNotificationText().setText(result);
                        AnimUtil.animateFadeIn(FragmentManagerClass.aMain.getNotificationContainer());
                    }

                }
                else
                    if (FragmentManagerClass.aMain != null) {
                        if (FragmentManagerClass.aMain.getNotificationContainer().getVisibility() == View.VISIBLE)
                            AnimUtil.animateFadeOut(FragmentManagerClass.aMain.getNotificationContainer(), null);
                    }

            }

        });
        nt.execute(Notifications.ACTION_GET_COUNT);

    }

    public void updateUserInformation(final boolean justPicture) {

        User us = new User();
        if (UserManagerClass.UserLogged == null)
            UserManagerClass.UserLogged = new UserManagerClass(getActivity()).getInfo();

        us.setID(UserManagerClass.UserLogged.getID());
        us.setCallbackGetInfo(new onGetUserInfoCompleted() {

            @Override
            public void Completed(User result) {

                setUserInfo(result);

                if (justPicture)
                    updateUserPicture();
                else
                    downloadUserProfilePicture(result);

            }
        });
        us.execute(User.ACTION_GET_INFO);

    }

    private void addItemsMenu() {

        items = new ArrayList<Item>();
        items.add(new Header(getResources().getString(R.string.dialog_loading_header)));
        adapter = new iconTextArrayAdapter(getActivity(), items);
        setListAdapter(adapter);

        //
        updateUserInformation(false);

    }

    private void addPopularTags(Tag[] result) {

        String[] arraymenu = this.getResources().getStringArray(R.array.array_slidingmenu);
        items.clear();
        items.add(new Header(this.getResources().getString(R.string.menu_header_social)));
        items.add(new ListItem(arraymenu[0], R.drawable.news_icon, SoapUtil.MODE_NEWS));
        items.add(new ListItem(arraymenu[1], R.drawable.explore_icon_menu, SoapUtil.MODE_EXPLORE));
        items.add(new ListItem(arraymenu[2], R.drawable.fav_icon_menu, SoapUtil.MODE_FAVS));
        items.add(new ListItem(arraymenu[3], R.drawable.friends_icon_menu, SoapUtil.MODE_FOLLOWERS));
        items.add(new ListItem(arraymenu[4], R.drawable.logout_icon, SoapUtil.MODE_LOGOUT));

        if (result != null && result.length > 0
                    && !result[0].getName().equals("-10")) {

            items.add(0, new Header(getResources().getString(R.string.menu_header_popular)));
            int cont = 1;
            for (Tag tg : result) {
                items.add(cont, new ListItemPopular(tg.getName(), String.valueOf(tg.getCount())));
                cont++;
            }

        }
        adapter.notifyDataSetChanged();

        edit.setVisibility(View.VISIBLE);

        FragmentManagerClass.aExplore.loadFrom(SoapUtil.MODE_NEWS, 0);

        UserManagerClass.updateState(1);
        //
        updateNotifications();
    }

    private void downloadPopularTags() {

        Tag tg = new Tag();
        tg.setCallbackSearch(new onSearchTagCompleted() {

            @Override
            public void Completed(Tag[] result) {

                addPopularTags(result);

            }
        });
        tg.execute(Tag.ACTION_GET_POPULAR);
    }

    private void downloadUserProfilePicture(User user) {

        ProfilePictureDownloader pd = new ProfilePictureDownloader();
        pd.setProgress(pload);
        pd.setCallbackProfilePicture(new onProfilePictureDownloaded() {

            @Override
            public void completed(Bitmap result) {

                setUserPicture(result);

            }
        });
        pd.execute(user.getProfilePicture());

    }

    private void inicializar() {

        FragmentManagerClass.aMenu = this;

        list = getListView();
        list.setOnItemClickListener(new MenuClickListener(getActivity(), ActivityMain.hmc));
        //
        // NOTIFICATION STUFF
        notificationContainer = (RelativeLayout) v.findViewById(R.id.container_notifications);
        notificationContainer.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(getActivity(), ActivityNotifications.class);
                getActivity().startActivity(intent);
                AnimUtil.getActivityTransition(getActivity(), true);

            }
        });
        notificationText = (TextView) v.findViewById(R.id.notification_text);
        notificationText.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                notificationContainer.performClick();

            }
        });
        notificationContainer.setVisibility(View.INVISIBLE);
        //
        name = (TextView) v.findViewById(R.id.text_header);
        UtilFonts.setTextBoldFont(name);
        UtilFonts.setTextRegularFont(notificationText);
        //
        edit = (ImageView) v.findViewById(R.id.menu_change_profile);
        edit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(profile.getContext(), ActivityProfile.class);
                startActivity(intent);
                AnimUtil.getActivityTransition(getActivity(), true);
            }
        });
        //
        profile = (ImageView) v.findViewById(R.id.image_profile);
        pload = (ProgressBar) v.findViewById(R.id.loading_progress);
        //
        edit.setVisibility(View.INVISIBLE);
        addItemsMenu();
        //

    }

    private void setUserPicture(Bitmap result) {

        this.profile.setImageBitmap(result);
        // //////////////////////////////////
        downloadPopularTags();
    }

    private void updateUserPicture() {

        ProfilePictureDownloader pd = new ProfilePictureDownloader();
        pd.setProgress(pload);
        pd.setCallbackProfilePicture(new onProfilePictureDownloaded() {

            @Override
            public void completed(Bitmap result) {

                profile.setImageBitmap(result);

            }
        });
        pd.execute(UserManagerClass.UserLogged.getProfilePicture());

    }

}
